package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

import com.model.Message;
import com.model.Users;
import com.mysql.jdbc.Statement;

@Component
public class MessageDao {
	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	
	 public ArrayList<Message> getList_hibernate(){
	        Session session = null;
	        Transaction tx = null;
	        session =  sessionFactory.openSession();
	        tx = session.beginTransaction();
	        Query query =session.createQuery("from Message");
	        List<Message> list = query.list();
	        tx.commit();
	        session.close();
	        return (ArrayList<Message>) list;
	    }
	
	

	public  void insert_hibernate(Message obj) {
		Session session = sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		session.save(obj);
		trans.commit();
		session.close();
	}
	
	
	
	public  void delete_hibernate(int id) {
		Session session = sessionFactory.openSession();
		//根据id获取Customer对象
		Message message = (Message) session.get(Message.class, id);
		System.out.println(message);
		Transaction tran=session.beginTransaction();
		session.delete(message);
		tran.commit();
		session.close();
	}
	

	
	public  Message found_hibernate(int id){
		Users u = null;
		Session session = sessionFactory.openSession();
		Message m = null;
		try{
		    session.beginTransaction();                    
		    m = (Message) session.get(Message.class, id);     //也可以用session.load(Fruit.class,"i001") 查询单个
		    session.getTransaction().commit();
		}
		catch(Exception es){
		    session.getTransaction().rollback();
		}
		return m;
	}
	
    public void updateData_hibernate(Message m){
        Session session= sessionFactory.openSession();        
        Transaction tx=session.beginTransaction();
        session.update(m);
        tx.commit();
        session.close();
    }
	
	
}
